package com.ysstech.schedule.service.impl;


import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysstech.common.entity.PageBean;
import com.ysstech.schedule.service.ScheduleJobService;
import com.ysstech.schedule.entity.ScheduleJob;
import com.ysstech.schedule.mapper.ScheduleJobMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2020-09-21
 */
@Service
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobMapper, ScheduleJob> implements ScheduleJobService {

    /**
     * 查询定时任务列表
     *
     * @param scheduleJob
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<ScheduleJob> listScheduleJob(ScheduleJob scheduleJob, PageBean pageBean) throws Exception {
        QueryWrapper<ScheduleJob> wrapper = this.getQueryWrapper(scheduleJob);
        IPage pageScheduleJob = this.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListRole(pageScheduleJob.getRecords());
        return new PageBean<>(pageScheduleJob);
    }


    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    private List<ScheduleJob> switchedListRole(List<ScheduleJob> list) throws Exception {
        for (ScheduleJob scheduleJob : list) {
            if (null == scheduleJob) {
                continue;
            }
        }
        return list;
    }

    /**
     * 查询条件
     *
     * @param scheduleJob
     * @return
     * @throws Exception
     */
    private QueryWrapper<ScheduleJob> getQueryWrapper(ScheduleJob scheduleJob) throws Exception {
        QueryWrapper<ScheduleJob> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("ADD_TIME");
        if (null == scheduleJob) {
            return wrapper;
        }
        if (StringUtils.isNotBlank(scheduleJob.getBeanName())) {
            wrapper.like("BEAN_NAME", scheduleJob.getBeanName());
        }
        if (StringUtils.isNotBlank(scheduleJob.getStrStatus())) {
            List<Integer> list = JSONArray.parseArray(scheduleJob.getStrStatus(), Integer.class);
            if (!CollectionUtils.isEmpty(list)) {
                wrapper.in("STATUS", list);
            }
        }
        return wrapper;
    }
}
